package com.ruoyi.web.controller.system;

import com.google.common.collect.Lists;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.base.BaseResult;
import com.ruoyi.common.enums.BusinessType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: dzx
 * @Date:Create：in 2020/7/17 0017 15:02
 * @Description:
 * @Modified By：
 * @Version: 1.0
 */
@RestController
public class UploadController {

    @Value("${dangjian.filePath}")
    private String filePath;

    /**
     * 修改保存分享设置
     */
    @Log(title = "上传图片", businessType = BusinessType.UPDATE)
    @PostMapping("/upload")
    public BaseResult uploadFile(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws IOException {
        if (file != null) {
            // 上传的文件名
            String filename = file.getOriginalFilename();
            String suffixName = filename.substring(filename.lastIndexOf("."));

            // 随机生成
            filename = UUID.randomUUID() + suffixName;
            File dest = new File(filePath + filename);
            try {
                file.transferTo(dest);

                return BaseResult.ok("/fileUpload/" + filename);
            } catch (IOException e) {
                e.printStackTrace();
                return BaseResult.notOk(Lists.newArrayList(new BaseResult.Error("io","文件传输异常")));
            }
        }
        return null;
    }

}
